package com.qf.admin.controller;

import cn.hutool.core.date.DateTime;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.qf.admin.domain.Jpush;
import com.qf.admin.domain.SendMessage;
import com.qf.admin.domain.User;
import com.qf.admin.mapper.JpushMapper;
import com.qf.admin.mapper.MessageMapper;
import com.qf.admin.service.IMessageService;
import com.qf.commons.Data;
import com.qf.commons.TableData;
import com.qf.pojo.QueryUser;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * @author He
 * @Date: 2020/10/22 11:26
 * @Description :
 */
@CrossOrigin("*")
@RestController
@RequestMapping("/message")
public class MessageController {

    public static final String APP_KEY = "9e8f37e14b228e89e618039f";
    public static final String MASTER_SECRET = "b3fc7efa1f3cc48b0fb574ce";

    private IMessageService messageServiceImpl;
    private MessageMapper messageMapper;
    private JpushMapper jpushMapper;

    public MessageController(IMessageService messageServiceImpl, MessageMapper messageMapper, JpushMapper jpushMapper) {
        this.messageServiceImpl = messageServiceImpl;
        this.messageMapper = messageMapper;
        this.jpushMapper = jpushMapper;
    }

    //分页查询
    @GetMapping("/getMessage")
    public TableData<SendMessage> getUsers(QueryUser queryUser,
                                           @RequestParam(defaultValue = "0") Integer offset,
                                           @RequestParam(defaultValue = "10") Integer limit) {
        if (!("".equals(queryUser.getName().trim())) && null != queryUser.getName()) {
            queryUser.setName("%" + queryUser.getName() + "%");
        }
        if ((!"".equals(queryUser.getTitle().trim())) && null != queryUser.getTitle()) {
            queryUser.setTitle("%" + queryUser.getTitle() + "%");
        }
        TableData<SendMessage> pageData = messageServiceImpl.getPageData(queryUser, offset, limit);

        return pageData;
    }

    //根据id查询
    @GetMapping("/getMessageById")
    public SendMessage getMessageById(Integer id) {
        return messageMapper.selectById(id);
    }

    @PostMapping("/putMessageById")
    public Data putMessageById(@RequestBody SendMessage editMessages) {
        messageMapper.updateById(editMessages);
        return new Data(1, "success");

    }

    @PostMapping("/sending")
    public Data sendMessage(String content, String addTitle, Integer userStatus) {
        Map<String, String> parms = new HashMap<>(8);
        SendMessage sendMessage = new SendMessage();
        sendMessage.setContent(content);
        sendMessage.setCreateTime(new Date());
        sendMessage.setTitle(addTitle);
        sendMessage.setUserId(userStatus);
        sendMessage.setName("root");
        sendMessage.setStatus(1);
        parms.put("id", null);
        try {
            if (userStatus > 0) {
                Jpush jpush = jpushMapper.selectById(userStatus);
                System.out.println("jpush" + jpush);
                String regId = jpush.getRegId();
                parms.put("id", regId);
            }
            parms.put("msg", content);
            jpushAndroid(parms, addTitle);
            messageMapper.insert(sendMessage);
            Integer id = sendMessage.getIds();
            System.out.println(id);
        } catch (Exception exception) {
            exception.printStackTrace();
            return new Data(-1, "fail");
        }
        return new Data(1, "success");

    }

    @PostMapping("/sendDelay")
    public Data sendMessageDelay(String content, String addTitle, String messageTime,Integer userStatus) {
        SendMessage sendMessage = new SendMessage();
        DateTime dateTime = new DateTime(messageTime, "yyyy-MM-dd HH:mm:ss");
        sendMessage.setPushTime(dateTime);
        sendMessage.setUserId(userStatus);
        sendMessage.setContent(content);
        sendMessage.setCreateTime(new Date());
        sendMessage.setTitle(addTitle);
        sendMessage.setName("root");
        sendMessage.setStatus(2);
        messageMapper.insert(sendMessage);
        return new Data(1, "success");
    }

    @PostMapping("/showContent")
    public SendMessage showContent(Integer id) {
        return messageMapper.selectById(id);

    }

    //批量删除
    @PostMapping("/deleteByDis")
    public Data deleteByDis(Integer[] ids) {
        List<Integer> list = new ArrayList<>();
        for (Integer id : ids) {
            list.add(id);
        }
        messageMapper.deleteBatchIds(list);
        return new Data(1, "success");

    }

    //批量删除
    @GetMapping("/getUser")
    public List<User> getUser() {
        return messageMapper.getUser();
    }

    //极光推送
    public void jpushAndroid(Map<String, String> parm, String title) {
        //创建JPushClient(极光推送的实例)
        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);
        //推送的关键,构造一个payload
        PushPayload payload = null;
        if (null != parm.get("id")&&!"".equals(parm.get("id").trim()) ) {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.android())
                    .setAudience(Audience.all())
                    .setAudience(Audience.registrationId(parm.get("id")))
                    .setNotification(Notification.android(parm.get("msg"), title, parm))
                    //发送内容
                    .setOptions(Options.newBuilder().setApnsProduction(false).build())
                    //这里是指定开发环境,不用设置也没关系
                    .setMessage(Message.content(parm.get("msg")))
                    .build();
        } else {
            payload = PushPayload.newBuilder()
                    //指定android平台的用户
                    .setPlatform(Platform.android())
                    //你项目中的所有用户
                    .setAudience(Audience.all())
                    .setNotification(Notification.android(parm.get("msg"), title, parm))
                    //发送内容
                    .setOptions(Options.newBuilder().setApnsProduction(false).build())
                    //这里是指定开发环境,不用设置也没关系
                    .setMessage(Message.content(parm.get("msg")))
                    .build();
        }
        try {
            PushResult pu = jpushClient.sendPush(payload);
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }
}
